//
//  LocationLabel.swift
//  WatermarkCamera
//
//  Created by 赵新 on 9/7/2024.
//

import UIKit
import RxRelay
import AxcBedrock

// MARK: - [LocationLabel.Format]

public extension LocationLabel {
    enum Format: Int {
        /// 地点
        case location
        /// 经纬度
        case longitudLatitude
        /// 中文经纬度
        case cn_longitudLatitude
    }
}

// MARK: - [LocationLabel]

open class LocationLabel: UILabel {
    // Lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)
        config()
    }

    @available(*, unavailable)
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Open

    /// 左边距
    open var leftEdge: CGFloat = 0

    /// 内容更新回调
    open var contentReloadBlock: AxcBlock.OneParam<String>?

    open override var text: String? {
        didSet {
            if let text = text {
                contentReloadBlock?(text)
            }
        }
    }

    open override func drawText(in rect: CGRect) {
        var rect = rect
        rect.origin.x = leftEdge
        rect.size.width -= leftEdge
        super.drawText(in: rect)
    }

    // Open

    /// 显示格式
    open var format: Format = .location {
        didSet { showText() }
    }

    /// 配置
    open func config() {
        text = "定位获取中..."

        // 监听定位
        LocationManager.shared.locatNameRelay.subscribe(onNext: { [weak self] str in
            guard let weakSelf = self else { return }
            weakSelf.locatNameRelay.accept(str)
            weakSelf.showText()
        }).disposed(by: rx.disposeBag)
    }

    let locatNameRelay: BehaviorRelay<String> = .init(value: "")

    // Internal

    /// 显示文字
    func showText() {
        if AuthorizedManager.location().info.isAvailable {
            var str = locatNameRelay.value
            text = str
        } else {
            text = "未开启定位权限"
        }
    }
}
